package com.infocollect.project.api.ui;


import com.alibaba.fastjson.JSON;
import com.infocollect.project.api.comm.WebApiHelper;
import com.infocollect.project.api.config.TokenService;
import com.infocollect.project.api.entity.TappDeptEntity;
import com.infocollect.project.api.entity.TappOrganEntity;
import com.infocollect.project.api.entity.TappUserEntity;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.JSONUtil;
import com.infocollect.project.api.helper.MapHelper;
import com.infocollect.project.api.req.NewLoginReq;
import com.infocollect.project.api.service.ITappDeptService;
import com.infocollect.project.api.service.ITappOrganService;
import com.infocollect.project.api.service.ITappUserService;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.api.vo.OrganSearchVO;
import com.infocollect.project.api.vo.TappUserVO;
import com.infocollect.project.api.vo.UserResultInfoVo;
import com.infocollect.project.form.vo.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (TappUser)表控制层
 *
 * @author makejava
 * @since 2019-12-25 10:32:31
 */
@Api(value = "tappUser", tags = "用户信息")
@RestController
@RequestMapping("tappUser")
public class TappUserController {
    /**
     * 服务对象
     */
    @Resource
    private ITappUserService tappUserService;
    /**
     * 服务对象
     */
    @Resource
    private ITappOrganService tappOrganService;
    /**
     * 服务对象
     */
    @Resource
    private ITappDeptService tappDeptService;
    /**
     * 用户登录接口
     *
     * @param post参数
     * @return 返回请求结果
     */
    @ApiOperation("用户登录")
    @PostMapping("login")
    @ResponseBody
    public R<String> login(@RequestBody Map<String,String> param){

        if(!StringUtils.isNotBlank(param.get("username")) ){
            return R.newError("用户不能为空！");
        }
        if(!StringUtils.isNotBlank(param.get("password")) ){
            return R.newError("密码不能为空！");
        }
        CurrentUserInfoVO currentUserInfo=  tappUserService.login(param.get("username"));
        // log.info("进入提交方法，username:"+ JackJson.objToJson(tappUser) );
        if(currentUserInfo==null){
            return R.newError("用户名或密码错误！");
        }
        if(param.get("password").equals(currentUserInfo.getPassword())){
            ////登录成功 创建token密钥
            currentUserInfo.setPassword("");
            String tokenstr= TokenService.Ins.getToken(JSONUtil.objToJson(currentUserInfo),param.get("password"));
            return  R.newOk(tokenstr);
        }else{
            return R.newError("用户名或密码错误！");
        }
    }

    /**
     * 用户登录接口
     *
     * @param post参数
     * @return 返回请求结果
     */
    @ApiOperation("用户登录")
    @PostMapping("newlogin")
    @ResponseBody
    public R<String> newlogin(@RequestBody NewLoginReq param) throws Exception {

        if(!StringUtils.isNotBlank(param.getUserId()) ){
            return R.newError("sessionId不能为空！");
        }
        String userinfJson= WebApiHelper.AjaxGet("http://127.0.0.1:8980/js/a/sys/user/info?__ajax=json&__sid="+param.getUserId());
        if(userinfJson.contains("sessionid")&&userinfJson.contains("result")){
              return R.newError("登录失败！");
        }
        UserResultInfoVo userResult= JSON.parseObject(userinfJson,UserResultInfoVo.class);
        userResult.user.setUsersessionid(param.getUserId());
        String tokenstr= TokenService.Ins.getToken(JSONUtil.objToJson(userResult.user),"userInfo");
        return  R.newOk(tokenstr);
    }
    @ApiOperation("用户退出登录")
    @PostMapping("logout")
    @ResponseBody
    public R<String> Logout(){
        return  R.newOk();
    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("获取用户信息")
    @PostMapping("selectOne/{id}")
    @ResponseBody
    public R<TappUserVO> selectOne(@PathVariable(name = "id") Long id) throws IOException {
        return R.newOk(this.tappUserService.queryById(id));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("删除用户信息")
    @PostMapping("del/{id}")
    @ResponseBody
    public R<String> Delete(@PathVariable(name = "id") Long id) throws IOException {
        if (this.tappUserService.deleteById(id)) {
            return R.newOk("操作成功！");
        } else {
            return R.newError("操作失败！");
        }
    }

    /**
     * 通过主键查询单条数据
     *
     * @param param post过来的参数
     * @return 单条数据
     */
    @ApiOperation("用户列表信息")
    @PostMapping("QueryUser")
    public R<List<TappUserEntity>> queryPageList(@RequestBody Map<String, String> param) throws Exception {

        TappUserEntity user = new TappUserEntity();
        user.setFdeptcode(param.get("code"));
        MapHelper.setObjectValue(user, param);
        int page = Integer.parseInt(param.get("page"));
        int rows = Integer.parseInt(param.get("rows"));
        PageHelper.startPage(page, rows);
        List<TappUserEntity> list = this.tappUserService.queryAll(user);
        PageInfo pageInfo = new PageInfo(list);
        return R.newOk(list,(int)pageInfo.getTotal());

    }

    /**
     * 保存机构信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("用户信息保存")
    @PostMapping("SaveData")
    @ResponseBody
    public  R<TappUserEntity> SaveData(@RequestBody Map<String, String> param) throws IOException {

        if (param.get("fusername") == null || param.get("fusername").length() == 0) {
            return R.newError("用户名称不能为空！");
        }
        if (param.get("frealaname") == null || param.get("frealaname").length() == 0) {
            return R.newError("真实名称不能为空！");
        }
        if (param.get("fduetime") == null || param.get("fduetime").length() == 0) {
            return R.newError("到期时间不能为空！");
        }
        try {
            TappUserEntity entity = param.get("fid") == null ? null : this.tappUserService.queryById(Long.parseLong(param.get("fid")));
            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            if (entity == null) {
                if (this.tappUserService.login(param.get("fusername")) != null) {
                    return R.newError("用户名称已存在！");
                }
                entity = new TappUserEntity();
                entity.setFcreateby(currentUserInfo.getUserName());
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFcreationdate(new Date());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity, param);
                entity.setFstate("1");
                entity.setFpassword("123456");
                if(entity.getFdeptcode()!=null) {
                    TappDeptEntity tappDept = tappDeptService.queryByCode(entity.getFdeptcode());
                    if(tappDept!=null){
                        entity.setFdeptid(tappDept.getFid());
                        entity.setForganid(tappDept.getForganid());
                    }
                }
                entity = this.tappUserService.insert(entity);

            } else {
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity, param);
                entity.setFusername(null);  ////用户名称是不能修改的
                entity.setFpassword(null);  ////用户密码是不能修改的
                entity = this.tappUserService.update(entity);
            }
            return R.newOk(entity);
        } catch (Exception ex) {
            return R.newError("保存失败！具体错误："+ex.toString());
        }

    }

    /**
     * 保存机构信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("停止与启动")
    @PostMapping("StopOrStart/{id}/{status}")
    @ResponseBody
    public  R<String> StopOrStart(@PathVariable(name = "id") Long id, @PathVariable(name = "status") String state) throws IOException {

        TappUserEntity entity = new TappUserEntity();
        entity.setFid(id);
        entity.setFstate(state);
        entity = this.tappUserService.update(entity);
        if (entity == null) {
            return R.newError("操作失败！");
        } else {
            return R.newOk("操作成功！");
        }

    }

    /**
     * 保存机构信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("重置密码")
    @PostMapping("ResetPassword/{id}")
    @ResponseBody
    public  R<String> ResetPassword(@PathVariable(name = "id") Long id) throws IOException {
        TappUserEntity entity = new TappUserEntity();
        entity.setFid(id);
        entity.setFpassword("123456");
        entity = this.tappUserService.update(entity);
        if (entity == null) {
            return R.newError("操作失败！");
        } else {
            return R.newOk("操作成功！");
        }

    }

    /**
     * 选择机构部门控件使用
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("选择用户")
    @PostMapping("SelectUser/{Search}")
    @ResponseBody
    public  R<List<OrganSearchVO>> SelectUser(@PathVariable(name = "Search") String Search) throws Exception {
        R<List<OrganSearchVO>> result=new R<>();
        List<TappOrganEntity> Organlist = new ArrayList<>();
        List<TappDeptEntity> Deptlist = new ArrayList<>();
        List<TappUserEntity> UserList = new ArrayList<>();
        TappDeptEntity DeptEntity = null;
        TappOrganEntity organEntity = null;
        TappDeptEntity parentdeptEntity = null;
        List<OrganSearchVO> searchList = new ArrayList<>();
        if (Search == null || Search.length() == 0||Search.equals("all")) {
            TappOrganEntity tappOrgan = new TappOrganEntity();
            tappOrgan.setForgancode("10001");
            Organlist = tappOrganService.queryAll(tappOrgan);
        } else {
            DeptEntity = tappDeptService.queryByCode(Search);
            if (DeptEntity != null) {
                organEntity = tappOrganService.queryById(DeptEntity.getForganid());
                Deptlist = tappDeptService.queryByParentID(DeptEntity.getFid());
                TappUserEntity tappUser = new TappUserEntity();
                tappUser.setFdeptid(DeptEntity.getFid());
                UserList = this.tappUserService.queryAll(tappUser);
                if (parentdeptEntity != null && parentdeptEntity.getFparentid() != null)
                    parentdeptEntity = tappDeptService.queryById(DeptEntity.getFparentid());
            } else {
                organEntity = tappOrganService.queryByCode(Search);
                TappDeptEntity tappDept = new TappDeptEntity();
                tappDept.setForganid(organEntity.getFid());
                Deptlist = tappDeptService.queryAll(tappDept);
                Organlist = tappOrganService.queryByParentID(organEntity.getFid());
            }

        }
        TappOrganEntity parentOrganEntity = null;
        if (organEntity != null && organEntity.getFparentid() != null)
            parentOrganEntity = tappOrganService.queryById(organEntity.getFparentid());
        for (int i = 0; i < Organlist.size(); i++) {
            TappOrganEntity ee = Organlist.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getForgancode());
            entity.setName(ee.getForganname());
            entity.setIsDept(0);
            if (organEntity != null) {
                entity.setDeptPNo(organEntity.getForgancode());
                entity.setDeptPName(organEntity.getForganname());// = organEntity.FOrganName;
                if (parentOrganEntity != null) {
                    entity.setGrandNo(parentOrganEntity.getForgancode());
                    entity.setGrandName(parentOrganEntity.getForganname());
                }
            }
            searchList.add(entity);
        }
        for (int i = 0; i < Deptlist.size(); i++) {
            TappDeptEntity ee = Deptlist.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getFdeptcode());
            entity.setName(ee.getFdeptname());
            entity.setIsDept(1);
            if (DeptEntity != null) {
                entity.setDeptPNo(DeptEntity.getFdeptcode());
                entity.setDeptPName(DeptEntity.getFdeptname());
                if (DeptEntity.getFparentid() == null) {
                    entity.setGrandNo(organEntity.getForgancode());
                    entity.setGrandName(organEntity.getForganname());
                } else {
                    entity.setGrandNo(parentdeptEntity.getFdeptcode());
                    entity.setGrandName(parentdeptEntity.getFdeptname());
                }
            } else {    ////公司下直属部门
                entity.setDeptPNo(organEntity.getForgancode());
                entity.setDeptPName(organEntity.getForganname());
                if (parentOrganEntity != null) {
                    entity.setGrandNo(parentOrganEntity.getForgancode());
                    entity.setGrandName(parentOrganEntity.getForganname());
                }
            }
            searchList.add(entity);
        }
        for (int i = 0; i < UserList.size(); i++) {
            TappUserEntity ee = UserList.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(ee.getFusername());
            entity.setName(ee.getFrealaname());
            entity.setRealName(ee.getFrealaname());
            if (organEntity != null) {
                entity.setGrandNo(organEntity.getForgancode());
                entity.setGrandName(organEntity.getForganname());
            }
            entity.setIsDept(2);
            entity.setDeptPName(DeptEntity.getFdeptname());
            entity.setDeptPNo(DeptEntity.getFdeptcode());
            searchList.add(entity);
        }
        return result.newOk(searchList);

    }
    /**
     * 搜索使用
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("搜索用户接口")
    @PostMapping("SearchUser/{Search}")
    @ResponseBody
    public R<List<OrganSearchVO>> SearchUser(@PathVariable(name = "Search") String Search) throws Exception{
        List<OrganSearchVO> searchList = new ArrayList<>();
        List<TappUserEntity>  UserList = this.tappUserService.queryUsernameOrRealaname(Search);
        for (int i = 0; i < UserList.size(); i++) {
            TappUserEntity user = UserList.get(i);
            TappDeptEntity deptEntity  = tappDeptService.queryById(user.getFdeptid());
            TappOrganEntity organEntity  = tappOrganService.queryById(user.getForganid());
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(user.getFusername());
            entity.setName(user.getFrealaname());
            entity.setRealName(user.getFrealaname());
            entity.setGrandNo( organEntity.getForgancode());
            entity.setGrandName(organEntity.getForganname()) ;
            entity.setIsDept(2) ;
            entity.setDeptPName(deptEntity.getFdeptname()) ;
            entity.setDeptPNo(deptEntity.getFdeptcode());
            searchList.add(entity);
        }
        return R.newOk(searchList);
    }
    /**
     * 搜索使用
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("获取当前登录用户")
    @PostMapping("GetCurrentUserInfo")
    @ResponseBody
    public CurrentUserInfoVO GetCurrentUserInfo()throws Exception{
        CurrentUserInfoVO currentUserInfo= CurrentHelp.Ins.GetUser();
        return currentUserInfo;

    }
    /**
     * 保存机构信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("保存当前用户信息")
    @PostMapping("SaveCurrentUserInfo")
    @ResponseBody
    public R<TappUserEntity>  SaveCurrentUserInfo(@RequestBody Map<String, String> param) throws Exception {
        if (param.get("FRealaName") == null || param.get("FRealaName").length() == 0) {
            return R.newError("真实名称不能为空！");
        }
        if (param.get("FPhone") == null || param.get("FPhone").length() == 0) {
            return R.newError("联系电话不能为空！");
        }
        CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
        TappUserEntity entity =new TappUserEntity();
        entity.setFid(currentUserInfo.getUserId());
        entity.setFlastupdateby(currentUserInfo.getUserName());
        entity.setFlastupdatedate(new Date());
        MapHelper.setObjectValue(entity, param);
        entity = this.tappUserService.update(entity);
        return R.newOk(entity);
    }

    /**
     *
     * @param param 修改密码
     * @return
     * @throws Exception
     */
    @ApiOperation("当前用户修改密码")
    @PostMapping("SaveCurrentPassWord")
    @ResponseBody
    public R<String>  SaveCurrentPassWord(@RequestBody Map<String, String> param) throws Exception {

        if (param.get("OldPassWord") == null || param.get("OldPassWord").length() == 0) {
            return R.newError("密码不能为空！");
        }
        if (param.get("NewPassWord") == null || param.get("NewPassWord").length() == 0) {
            return R.newError("新密码不能为空！");
        }
        if (!param.get("NewPassWord").equals(param.get("RetryPassWord"))) {
            return R.newError("两次密码不一致！");
        }
          CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
          String passWord= tappUserService.queryById(currentUserInfo.getUserId()).getFpassword();
          if(!param.get("OldPassWord").equals(passWord)){
              return R.newError("输入的密码不正确！！");
          }
        TappUserEntity entity =new TappUserEntity();
        entity.setFid(currentUserInfo.getUserId());
        entity.setFpassword(param.get("NewPassWord"));
        entity = this.tappUserService.update(entity);
        return R.newOk("修改密码成功！");
    }
    /**
     *修改头像
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation("当前用户修改头像")
    @PostMapping("SaveCurrentHeadImg")
    @ResponseBody
    public R<String> SaveCurrentHeadImg(@RequestBody Map<String, String> param)throws Exception{
        CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
        TappUserEntity entity =new TappUserEntity();
        entity.setFid(currentUserInfo.getUserId());
        entity.setFheadimg(param.get("HeadImg"));
        entity = this.tappUserService.update(entity);
        return R.newOk("修改密码成功！");
    }
}
